from starlette import status
from starlette.middleware.base import BaseHTTPMiddleware
from fastapi import Request
from traceback import format_exc

from starlette.responses import JSONResponse

from app.dependencies import request_id
from app.config import appLogger

class ErrorHandingMiddleware(BaseHTTPMiddleware):
  async def dispatch(self, request: Request, call_next):
    try:
      response = await call_next(request)
      return response
    except Exception as exc:
      appLogger.error("request exception", extra={"requestId":request_id.get(), "code":500, "error":str(exc), "stack":format_exc()})
      # return JSONResponse(content={"msg": str(exc)}, status_code=500)
      return JSONResponse(
        status_code=status.HTTP_200_OK,
        content={
          "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
          "msg": str(exc),
        }
      )

